package com.jk.smartelderlycare.controller;

import com.jk.smartelderlycare.dao.TbOrderRepository;
import com.jk.smartelderlycare.entity.TbOrder;
import com.jk.smartelderlycare.pojo.ResponseResult;
import com.jk.smartelderlycare.security.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author hhk
 * @version 1.0
 * @ClassName TbOrderController
 * @program: smart-elderly-care
 * @description: TODO
 * @date 2024/12/2 20:07
 */
@Api(tags = "订单管理模块")
@RestController
@Slf4j
@RequestMapping(value = "order")
public class TbOrderController {
    @Autowired
    private TbOrderRepository tbOrderRepository;

    @Autowired
    private AmqpTemplate amqpTemplate;


    @ApiOperation(value = "新增订单",httpMethod = "POST",notes = "新增订单")
    @PostMapping(value = "addTbOrder")
    private ResponseResult<TbOrder> addTbOrder(@RequestBody TbOrder tbOrder){
        try {
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            tbOrder.setLoginName(loginUser.getUser().getUsername());
            tbOrder.setState("未支付");
            tbOrder.setCreationTime(new Date());
            TbOrder order = tbOrderRepository.save(tbOrder);
            System.out.println("新增的数据为"+order);
            return new ResponseResult(200,"新增成功",order);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500,"新增失败");
        }
    }
    /** 
     * @description: 根据id查询订单
     * @param: [ordersId]
     * @return: com.jk.smartelderlycare.pojo.ResponseResult
     * @author hhk
     * @date: 2024/12/3 14:12
     */ 
    @ApiOperation(value = "根据id查询订单",httpMethod = "GET",notes = "根据id查询订单")
    @GetMapping(value = "findTbOrderById")
    private  ResponseResult findTbOrderById(@RequestParam("ordersId") String ordersId){

        try {
            TbOrder tbOrder = tbOrderRepository.findById(ordersId).get();
            tbOrder.setState("已支付");
//            TbOrder order = tbOrderRepository.save(tbOrder);
            System.out.println("发送消息topicExchange" + tbOrder.toString());
            amqpTemplate.convertAndSend("exchangeA", "Tborder.message", tbOrder);

            return new ResponseResult(200,"查询修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500,"查询失败");
        }

    }


    
    



}
